<?php
// 这个文件是触发红包的
require_once 'AopSdk.php';
require_once 'function.inc.php';
require_once 'config.php';
require_once 'MysqliDb.php';
require_once 'HttpRequst.php';

/*$data = array('msg' =>'活动还未开始' ,'code' =>'100' );
exit(json_encode($data));*/

$db = new MysqliDb ($configDb);
$user_id=  HttpRequest::getRequest ( "user_id" );
$results =$db
	->where ('status', 1)
 	->getOne('crowd');

if(empty($results)){ // 没找到订单返回错误信息
	$data = array('msg' =>'缺少订单号' ,'code' =>'100' );
	exit(json_encode($data));
}

if (empty($user_id)){
	$data = array('msg' =>'参数错误' ,'code' =>'101' );
	exit(json_encode($data));
}

$res =$db
	->where ('alipay_user_id', $user_id)
	->getOne('user');
$count = $db
      ->where ('alipay_user_id', $user_id) 
      ->getValue ("user", "count(*)");
if ($count==0){
	$data = array('msg' =>'参数错误' ,'code' =>'102' );
	exit(json_encode($data));
}
if (empty($res)) {
	// 没有用户信息怎么可能分享红包的防止作弊
	$data = array('msg' =>'参数错误' ,'code' =>'102' );
	exit(json_encode($data));
}
$countH = $db
      ->where ('alipay_user_id', $user_id) 
      ->getValue ("hongbao", "count(*)");
if ($countH>0){
	$re = $db
      ->where ('alipay_user_id', $user_id) 
      ->getOne ("hongbao");

	$data = array('msg' =>'Success' ,'code' =>'10000','prize_amount'=> $re['prize_amount']);
	exit(json_encode($data));
}
$aop = new AopClient ();
$aop->gatewayUrl = $config['gatewayUrl'];
$aop->appId = $config['app_id'];
$aop->rsaPrivateKey = $config['merchant_private_key'];
$aop->alipayrsaPublicKey=$config['alipay_public_key'];
$aop->apiVersion = '1.0';
$aop->signType = $config['sign_type'];
$aop->postCharset='utf-8';
$aop->format='json';
$request = new AlipayMarketingCampaignCashTriggerRequest ();
$request->setBizContent("{" .
"\"user_id\":\"".$user_id."\"," .
"\"crowd_no\":\"".$results['crowd_no']."\"," .
"\"order_price\":\"".rand(5,15)."\"," . //单位分
"  }");
$result = $aop->execute ( $request); 

$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
$resultCode = $result->$responseNode->code;
$repeat_trigger_flag= $result->$responseNode->repeat_trigger_flag; //是否重复领取
$arr=object_array($result->$responseNode);
if(!empty($resultCode)&&$resultCode == 10000){
	// 成功录入数据库呗
	$t=time();
	$data = array(
		'alipay_user_id'=>$user_id,
		'prize_amount' => $result->$responseNode->prize_amount, 
		'biz_no'=>$result->$responseNode->biz_no,
		'create_time'=>$t
	);
	$id = $db->insert ('hongbao', $data);
	if ($id){}
}

exit(json_encode($arr)) ;
